package com.ikingtech.platform.service.job.controller;

import com.ikingtech.framework.sdk.context.constant.SecurityConstants;
import com.ikingtech.framework.sdk.core.response.R;
import com.ikingtech.framework.sdk.job.api.JobApi;
import com.ikingtech.framework.sdk.enums.job.JobStatusEnum;
import com.ikingtech.framework.sdk.job.model.JobDTO;
import com.ikingtech.framework.sdk.job.scheduler.JobScheduler;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.framework.sdk.web.annotation.ApiController;
import com.ikingtech.platform.service.job.entity.JobDO;
import com.ikingtech.platform.service.job.service.JobRepository;
import com.ikingtech.platform.service.job.service.JobService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author tie yan
 */
@Slf4j
@RequiredArgsConstructor
@ApiController(value = "/job", name = "调度中心", description = "调度中心")
public class JobController implements JobApi {

    private final JobService service;

    private final JobRepository repository;

    private final JobScheduler<JobDO> scheduler;

    /**
     * 启动定时任务
     *
     * @param job 任务信息
     * @return 执行结果
     */
    @Override
    public R<Object> start(JobDTO job) {
        JobDO entity = Tools.Bean.copy(job, JobDO.class);
        entity.setId(Tools.Id.uuid());
        entity.setTenantCode(SecurityConstants.DEFAULT_TENANT_CODE);
        entity.setStatus(JobStatusEnum.RUNNING.name());
        this.repository.save(entity);
        this.scheduler.schedule(this.service.createScheduledJob(entity));
        return R.ok(entity.getId());
    }

    /**
     * 停止定时任务
     *
     * @param jobId 任务信息
     * @return 执行结果
     */
    @Override
    public R<Object> stop(String jobId) {
        JobDO entity = this.repository.getById(jobId);
        if (null == entity) {
            return R.ok();
        }
        entity.setStatus(JobStatusEnum.END.name());
        this.repository.updateById(entity);
        this.scheduler.cancel(jobId);
        return R.ok();
    }
}
